package com.yangcangclub.commons.velocity;

import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

/**
 * 模板资源加载器(由模板资源提供者完成)
 *
 *
 */
@Component
public class TemplateResourceLoader extends ResourceLoader {

    @Autowired
    private IVMTemplateProvider ivmTemplateProvider;

    /**
     * 得到最后一次修改时间
     */
    @Override
    public long getLastModified(Resource resource) {
        String name = resource.getName();
        long timeStamp = this.ivmTemplateProvider.getTplVersion(name);
        return timeStamp;
    }

    /**
     * 通过提供者得到具体文件中信息
     */
    @Override
    public synchronized InputStream getResourceStream(final String name)
            throws ResourceNotFoundException {
        //根据名称得到文件信息
        String vmSource = this.ivmTemplateProvider.getVMSource(name);
        if (vmSource == null) {
            throw new ResourceNotFoundException("名称为[" + name + "]的模板不存在");
        }

        byte[] data;
        try {
            //转为字节数组存储
            data = vmSource.getBytes(this.ivmTemplateProvider.defaultCharset().name());
            return new ByteArrayInputStream(data);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 初始化工作
     */
    @Override
    public void init(ExtendedProperties arg0) {
    }

    /**
     * 判断文件是否修改
     */
    @Override
    public boolean isSourceModified(Resource resource) {
        long nowVersion = getLastModified(resource);
        long lastVersion = resource.getLastModified();
        return nowVersion != lastVersion;
    }

    public IVMTemplateProvider getTemplateProvider() {
        return ivmTemplateProvider;
    }

    public void setTemplateProvider(IVMTemplateProvider templateProvider) {
        this.ivmTemplateProvider = templateProvider;
    }
}
